package com.jiumi.api.controller;


import com.jiumi.api.base.BaseApiController;
import com.jiumi.api.util.WeiXinUtil;
import com.jiumi.api.vo.WxLoginVo;

import com.jiumi.baseconfig.domain.BaseBannerInfo;
import com.jiumi.baseconfig.domain.BaseChapter;
import com.jiumi.baseconfig.domain.BaseCourseInfo;
import com.jiumi.baseconfig.domain.BaseUser;
import com.jiumi.baseconfig.service.IBaseChapterService;
import com.jiumi.baseconfig.service.IBaseCourseInfoService;
import com.jiumi.baseconfig.service.IBaseUserService;
import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.core.domain.R;
import com.jiumi.common.core.page.TableDataInfo;
import com.jiumi.common.core.redis.RedisCache;
import com.jiumi.common.utils.DateUtils;
import com.jiumi.config.WeiXinConfig;
import com.jiumi.order.domain.BaseOrderInfo;
import com.jiumi.order.service.IBaseOrderInfoService;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lun.zhang
 * @create 2022/10/18 18:29
 */
@RestController
@RequestMapping("/api")
public class UserApiController extends BaseApiController {

    @Autowired
    private WeiXinConfig weiXinConfig;
    @Autowired
    private WeiXinUtil weiXinUtil;
    @Autowired
    private IBaseUserService userInfoService;


    @Autowired
    private IBaseChapterService baseChapterService;

    @Autowired
    private IBaseCourseInfoService baseCourseInfoService;

    @Autowired
    private IBaseOrderInfoService baseOrderInfoService;

    @Autowired
    private RedisCache redisCache;
    /**
     * 获取微信手机号
     *
     * @param wxLoginVo wx登录签证官
     * @return {@link AjaxResult}
     */
    @PostMapping("/user/getWxPhoneNumber")
    public AjaxResult getPhoneNumberV2(@RequestBody WxLoginVo wxLoginVo) {
        return AjaxResult.success("", weiXinUtil.getWxPhoneNumber(wxLoginVo.getCode()));

    }


    /**
     * 更新用户信息
     *
     * @param userInfo
     * @return {@link AjaxResult}
     */
    @PostMapping("/user/updateUserInfo")
    public AjaxResult updateUserDetail(@RequestBody BaseUser userInfo) {
        Long userId = getUserId();
        userInfo.setUserId(userId);
        userInfo.setPassword(null);
        int result=userInfoService.updateBaseUser(userInfo);
        return toAjax(result);

    }

    @GetMapping("/user/getUserDetail")
    public AjaxResult getUserDetail() {
        Long userId = getUserId();
        BaseUser userInfo = userInfoService.selectBaseUserByUserId(userId);
        userInfo.setPassword("");
        return AjaxResult.success(userInfo);
    }

    /**
     * 课程详细信息
     */
    @GetMapping(value = "/getCourseDetail")
    public R<BaseCourseInfo> getCourseDetail(@RequestParam(value = "id", required = true) Long id)
    {
        BaseCourseInfo courseInfo=baseCourseInfoService.selectBaseCourseInfoById(id);
        if(courseInfo==null){
            return R.fail("未查询到课程信息");
        }

        Long userId=null;
        try{
            userId=getUserId();
        }
        catch (Exception e){
            logger.info(e.getMessage());
        }
        List<BaseCourseInfo> buyList=new ArrayList<>();
        if(userId!=null){
            BaseUser userInfo= userInfoService.selectBaseUserByUserId(userId);
            if(userInfo!=null){
                buyList=baseCourseInfoService.selectUserBuyCourseInfoList(userInfo.getUserId());
            }
        }
        BaseChapter param=new BaseChapter();
        param.setCourseId(courseInfo.getId());
        List<BaseChapter> chapterList= baseChapterService.selectBaseChapterList(param);

        courseInfo.setUserBuyFlag("N");
        BaseCourseInfo checkBuyFlag=buyList.stream().filter(course->course.getId().intValue()==courseInfo.getId().intValue()).findFirst().orElse(null);
        if(checkBuyFlag==null){
            chapterList.stream().forEach(cht->{
                cht.setVideoUrl(null);
            });
        }else{
            courseInfo.setUserBuyFlag("Y");
        }
        courseInfo.setChapterList(chapterList);

        BaseCourseInfo courseParam=new BaseCourseInfo();
        courseParam.setCourseTypeId(courseInfo.getCourseTypeId());
        courseParam.setId(courseInfo.getId());
        List<BaseCourseInfo> relateCourseList=baseCourseInfoService.selectRelateCourseInfoList(courseParam);
        courseInfo.setRelaCourseList(relateCourseList);
        return R.ok(courseInfo);
    }

    /**
     * 查询订单信息列表
     */
    @GetMapping("/getUserOrders")
    public TableDataInfo getUserOrders(BaseOrderInfo baseOrderInfo)
    {
        baseOrderInfo.setUserId(getUserId());
        startPage();
        List<BaseOrderInfo> list = baseOrderInfoService.selectUserOrderInfoList(baseOrderInfo);
        return getDataTable(list);
    }


    /**
     * 查询用户购买课程
     */
    @GetMapping("/getUserCourse")
    public R<List<BaseCourseInfo>> getUserCourse(BaseCourseInfo courseInfo)
    {
        courseInfo.setId(getUserId());
        List<BaseCourseInfo> buyList=baseCourseInfoService.selectUserBuyCourseList(courseInfo);
        return R.ok(buyList);
    }

    /**
     * 获取学籍号
     * @param userPhone 手机号
     * @param code 验证码
     * @return
     */
    @GetMapping("/user/createStuCode")
    public AjaxResult createStuCode(@RequestParam(value = "userPhone", required = true) String userPhone,
                                    @RequestParam(value = "code", required = false) String code) {
        String key = "phone_verify_code" + userPhone;
        String checkCode = redisCache.getCacheObject(key) + "";
        /*if (!code.equals(checkCode)) {
            return AjaxResult.error("验证码错误");
        }*/
        BaseUser userInfo=  userInfoService.selectBaseUserByUserPhone(userPhone);
        BaseUser currentUser=getLoginUser().getUserInfo();
        String stuCodeStr=String.valueOf(System.currentTimeMillis());
        String stuCode=stuCodeStr.substring(5);
        AjaxResult result=AjaxResult.success();
        result.put("userPhone",userPhone);
        result.put("stuCode",stuCode);
        BaseUser editUser=new BaseUser();
        editUser.setUserId(currentUser.getUserId());
        editUser.setStudentId(stuCode);
        editUser.setUpdateTime(DateUtils.getNowDate());
        if(userInfo!=null){
            if(currentUser.getUserName().equals(userInfo.getUserName())){
                userInfoService.updateBaseUser(editUser);
                return result;
            }else{
                return AjaxResult.error("当前账号与手机号对应账号不一致，请联系管理员");
            }
        }else{
            userInfoService.updateBaseUser(editUser);
            return result;
        }
    }
}
